/**
 * \file strutil.cpp
 *
 * strutil - version 1.01
 * Written 2010-2011, by Anton Berlin
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "strutil.h"

bool strutil::contains_only_whitespaces(string& str)
{
    for (unsigned int i = 0; i < str.length(); ++i)
    {
        switch (str[i])
        {
            case ' ':
            case '\n':
            case '\r':
            case '\t':
                break;
            default:
                return 0;
        }
    }

    return 1;
}

string* strutil::strip_extra_whitespaces(string& str, string* target)
{
    (*target) = "";

    if (str.empty())
    {
        return target;
    }

    string temp;
    char curChar;

    bool insideString = false;
    bool insideChar = false;

    for (unsigned int index = 0; index < str.length(); ++index)
    {
        curChar = str[index];

        if (str[index] == '"' && !insideChar)
        {
            if (!insideString)
                insideString = true;
            else
                insideString = false;

            temp += str[index];
        }
        else if (str[index] == '\'' && !insideString)
        {
            if (!insideChar)
                insideChar = true;
            else
                insideChar = false;

            temp += str[index];
        }
        else if ((str[index] != ' '
                && str[index] != '\t'
                && str[index] != '\n'
                && str[index] != '\r')
                || insideString
                || insideChar)
            temp += str[index];
        else if (!temp.empty())
        {
            (*target) += temp;

            if (index < str.length())
                (*target) += ' ';

            temp = "";
        }
    }

    if (!temp.empty())
        (*target) += temp;

    return target;
}

string& strutil::cap(string& str)
{
    str[0] = toupper(str[0]);
    return str;
}
